package com.illtamer.infinite.sillage.controller;

import com.illtamer.infinite.derive.Path;
import com.illtamer.infinite.derive.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping
public class ResourceController {

    // TODO global config object
    private final Path root = Resource.instance().root("source");

    @RequestMapping("/resource")
    public void resource(@RequestParam(value = "download", required = false) Boolean download,
                           HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (download != null && download) {
            request.getRequestDispatcher("/resource-download").forward(request, response);
        } else {
            request.getRequestDispatcher("/resource-page").forward(request, response);
        }
    }

    @RequestMapping("/resource/**")
    public void redirectResource(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String relativePath = request.getRequestURI().substring(9);
        final Path path = Resource.getPath(root, relativePath);
        if (path == null) return;
        if (path.isDirectory()) {
            response.sendRedirect("/resource?init=true&relativePath=" + relativePath);
        } else {
            request.getRequestDispatcher("/resource-download?relativePath=" + relativePath).forward(request, response);
        }
    }

    @RequestMapping("/resource-page")
    public String page(@RequestParam(value = "relativePath", required = false) String relativePath,
                       @RequestParam(value = "init", required = false, defaultValue = "false") Boolean init,
                       Model model) {
        if (init) { // 片段 初始化
            model.addAttribute("root", Resource.getPath(root, relativePath));
            return "resource";
        } else if (relativePath == null || relativePath.length() == 0) { // 根节点 （默认初始化
            model.addAttribute("root", root);
            return "resource";
        } else { // 片段
            model.addAttribute("root", Resource.getPath(root, relativePath));
            return "resource::resourceList";
        }
    }

    @RequestMapping("/resource-download")
    public void download(@RequestParam(value = "relativePath") String relativePath,
                         HttpServletResponse response) throws UnsupportedEncodingException {
        final Path path = Resource.getPath(root, relativePath);
        if (path == null) return;

        // 标记返回类型与文件名称
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(path.getName(), "UTF-8"));

        int length;
        byte[] bytes = new byte[1024];
        try (
                ServletOutputStream output = response.getOutputStream();
                InputStream input = path.getInputStream()
        ) {
            while ((length = input.read(bytes)) != -1)
                output.write(bytes, 0, length);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
